﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnalisisDeRiesgos.Models.Report;
using AnalisisDeRiesgos.Models;
using Microsoft.Web.Mvc;
using CrystalDecisions.CrystalReports.Engine;
using AnalisisDeRiesgos.Models.Danger;
using System.IO;

namespace AnalisisDeRiesgos.Controllers
{
    public class ReportController : Controller
    {
        //
        // GET: /Report/
        public ActionResult Index()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.AreaSecurity))
                return RedirectToAction("LogOn", "User");
            return View();
        }

        //
        // GET: /Report/Schedules
        public ActionResult Schedules()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.AreaSecurity))
                return RedirectToAction("LogOn", "User");

            ScheduleModel model = new ScheduleModel();
            model.TheDate = DateTime.Today.ToString("d", Utils.culture).Replace('/', '-');

            model.Search();
            return View(model);
        }

        [AcceptAjax]
        public PartialViewResult GetScheduleFromDate(string id)
        {
            if (id == null)
                return PartialView("ErrorPartial", new ErrorModel { Message = "La fecha no puede ser nula" });
            
            ScheduleModel model = new ScheduleModel();
            model.TheDate = id;
            model.Search();
            return PartialView("SchedulesList", model.Actions);
        }

        public ActionResult PotentialDanger()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");
            ReportClass report = new ReportClass();
            report.FileName = Server.MapPath("~/Models/Report/PotentialDanger.rpt");
            report.Load();
            PotentialDangerModel model = new PotentialDangerModel();
            model.SearchDanger();
            report.SetDataSource(model.DangerInfo);
            Stream stream = report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }
    }
}
